﻿// <copyright file="EditCategory.aspx.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using Auros.Categorisation.Data;
using umbraco.BasePages;
using umbraco.cms.businesslogic;
using Umbraco.Core.IO;

namespace Auros.Categorisation.Umbraco
{
    /// <summary>
    /// Class defining the category editor page.
    /// </summary>
    public partial class EditCategory : UmbracoEnsuredPage
    {
        private int currentCategoryId;
        private Category currentCategory;

        private string umbracoBaseUrl = IOHelper.ResolveUrl(SystemDirectories.Umbraco);

        /// <summary>
        /// Raises the <see cref="E:Init"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ImageButton saveButton = this.PropertyPanel.Menu.NewImageButton();
            saveButton.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            saveButton.AlternateText = UIHelpers.GetLocalisedText("save", "actions", "Save");

            saveButton.Click += new System.Web.UI.ImageClickEventHandler(this.SaveButton_Click);

            this.currentCategoryId = -1;

            if (int.TryParse(this.Request["id"], out this.currentCategoryId))
                this.currentCategory = new CategoryRepository().GetCategory(this.currentCategoryId);

            this.ConfigureDictionaryLinks();
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.DataBind();

            if (!Page.IsPostBack)
                this.FillFormElements();
        }

        /// <summary>
        /// Handles the Click event of the SaveButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        protected void SaveButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.currentCategory.Name = this.NameTextBox.Text;
            this.currentCategory.Description = this.DescriptionTextBox.Text;
            this.currentCategory.Selectable = this.SelectableCheckBox.Checked;
            this.currentCategory.Enabled = this.EnabledCheckBox.Checked;

            // Save changes.
            new CategoryRepository().Update(currentCategory);

            string path = this.GetCategoryTreePath(this.currentCategoryId);

            BasePage.Current.ClientTools.SyncTree(path, true);
        }

        /// <summary>
        /// Fills the form elements.
        /// </summary>
        private void FillFormElements()
        {
            this.IDLabel.Text = this.currentCategory.ID.ToString();
            this.NameTextBox.Text = this.currentCategory.Name;
            this.DescriptionTextBox.Text = this.currentCategory.Description;
            this.SelectableCheckBox.Checked = this.currentCategory.Selectable;
            this.EnabledCheckBox.Checked = this.currentCategory.Enabled;
        }

        /// <summary>
        /// Gets the category tree path.
        /// </summary>
        /// <param name="id">The category id.</param>
        /// <returns>CSV path of the given category.</returns>
        private string GetCategoryTreePath(int id)
        {
            List<int> pathItems = new List<int>(10) { id };

            var categories = new CategoryRepository().GetCategories().ToList();

            Func<int, List<int>> build = null;

            build = (cId) =>
            {
                var a = (from x in categories where x.ID == cId && x.Parent != null && x.Parent.ID > 0 select x.Parent.ID).ToList();

                if (a.Count > 0)
                    a.AddRange(build(a[a.Count - 1]));

                return a;
            };

            pathItems.AddRange(build(id));

            pathItems.Reverse();

            StringBuilder path = new StringBuilder();

            for (int i = 0; i < pathItems.Count; i++)
            {
                path.Append(pathItems[i]);

                if (i + 1 < pathItems.Count)
                    path.Append(',');
            }

            return path.ToString();
        }

        /// <summary>
        /// Configures the dictionary links.
        /// </summary>
        private void ConfigureDictionaryLinks()
        {
            if (StringHelpers.DictionaryItemExists(this.currentCategory.Name))
            {
                var dictionaryItem = new Dictionary.DictionaryItem(this.currentCategory.Name);

                this.NameTranslateLink.NavigateUrl = umbracoBaseUrl + "/settings/editDictionaryItem.aspx?id=" + dictionaryItem.id;
            }
            else
                this.NameTranslateLink.Visible = false;

            if (StringHelpers.DictionaryItemExists(this.currentCategory.Name + "_Description"))
            {
                var dictionaryItem = new Dictionary.DictionaryItem(this.currentCategory.Name + "_Description");

                this.DescriptionTranslateLink.NavigateUrl = umbracoBaseUrl + "/settings/editDictionaryItem.aspx?id=" + dictionaryItem.id;
            }
            else
                this.DescriptionTranslateLink.Visible = false;
        }
    }
}